package client.comm.baoding.ui.vm

import android.app.Application
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import client.comm.commlib.network.data.JsonResult
import client.comm.commlib.network.data.Ret
import client.comm.commlib.out_time
import client.comm.commlib.toast.toast
import client.comm.commlib.utils.StoreUtil
import client.comm.baoding.ui.viewmodel.MiddleVm
import client.comm.baoding.api.bean.UserInfo
import client.comm.baoding.api.bean.Zcjl
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import retrofit2.Response

class QbyeViewModel(app: Application) : MiddleVm(app) {
    val call = MutableLiveData<JsonResult<Ret>>()
    val isShowing = MutableLiveData<Boolean>()
    val isOneLoading = MutableLiveData<Boolean>(false)
    val pageOne = MutableLiveData<Int>(0)
    val callOne = MutableLiveData<JsonResult<Zcjl>>()

    fun holdOne() {
        if (isOneLoading.value!!)
            return
        hold({
            server.zcjl(pageOne.value!!, 1)
        }, {
            isOneLoading.value = true
            pageOne.value = pageOne.value!! + 1
        }, {
            callOne.value = it
        }, complete = {
            isOneLoading.value = false
        })
    }

    /**
     */
    fun ok(it: String) {
        isShowing.value = true
        viewModelScope.launch {
            flow {
                var emm: Response<JsonResult<Ret>>? = null
                out_time {
                    val ret = server.validatePayPwd(it)
                    emm = ret
                }
                emit(emm)
            }.map {
                var emm: Response<JsonResult<Ret>>? = it
                it?.body()?.let {
                    if (it.isSuccess) {
                        var payType = "1"
                        val user = StoreUtil.getBean<UserInfo>(getApplication())
                        out_time {
                            val ret = server.tx("11", "1", payType, "", user!!.phone)
                            emm = ret
                        }
                    }
                }
                emm
            }.flowOn(Dispatchers.IO)
                .onCompletion {
                    isShowing.value = false
                }.catch { cause ->
                    if (cause != null) {
//                        toast(cause.message)
                        toast("网络错误")
                    }
                }.collectLatest {
                    call.value = it?.body()
                }
        }
    }

    fun getData() {
//        hold({
//        }, {
//
//        }, {
//            call.value = it?.body()
//        })
    }

}